package xyz.xuminghai.javafx_learn.concurrent;

import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 2023/5/19 23:17 星期五<br/>
 * Service 组件示例
 *
 * @author xuMingHai
 */
public class ServiceApp extends Application {

    private final HBox hBox = new HBox(30.0);

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void init() {
        Button startButton = new Button("start");

        TextArea textArea = new TextArea();
        textArea.setPrefSize(200.0, 100.0);
        // 设置换行
        textArea.setWrapText(true);

        Service<String> service = new Service<>() {
            @Override
            protected Task<String> createTask() {
                return new Task<>() {
                    @Override
                    protected String call() throws IOException, URISyntaxException {
                        String fileName = "service-app.txt";
                        URL url = getClass().getResource(fileName);
                        if (url == null) {
                            throw new FileNotFoundException(fileName);
                        }
                        return Files.readString(Path.of(url.toURI()));
                    }
                };
            }

            @Override
            protected void succeeded() {
                textArea.setText(getValue());
            }

        };

        startButton.setOnAction(event -> {
            if (Worker.State.READY == service.getState()) {
                service.start();
            } else {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setContentText("Service状态不为READY");
                alert.show();
            }
        });


        hBox.setAlignment(Pos.CENTER);
        hBox.setFillHeight(false);
        hBox.getChildren().addAll(startButton, textArea);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle(getClass().getSimpleName());
        Scene scene = new Scene(hBox, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
